package com.samapp;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dragon.httpclient_util.HttpClientThread;
import com.dragon.httpclient_util.HttpResultHandle;
import com.dragon.httpclient_util.JsonUtils;
import com.samapp.base.BaseActivity;
import com.samapp.db.SamappDB;
import com.samapp.entity.Client;
import com.samapp.entity.User;
import com.samapp.utils.json.GsonUtil;

public class LoginActivity extends BaseActivity implements OnClickListener {

	private Button btnLogin = null;
	private EditText mUsername = null;
	private EditText mPassword = null;
	private String username;
	private String password;
	/** 登录失败提示 */
	private TextView textviewFailure = null;
	/** 下拉选择用户名 */
	private ImageView downSelect = null;
	private MyApplication myApplication = MyApplication.getApplicationInstance();
	/** 登录 */
	public static final int MSG_LOGIN = 0x190;
	/** 登录失败信息 */
	private String loginFailure;
	/** 获取所有用户 */
	public static final int MSG_GET_ALL_CLIENT = 0x191;
	/** 获取客户信息异常信息 */
	private String getClientFailure;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == MSG_LOGIN) {
				textviewFailure.setVisibility(View.VISIBLE);
				textviewFailure.setText(loginFailure);
			} else if (msg.what == MSG_GET_ALL_CLIENT) {
				Toast.makeText(LoginActivity.this, getClientFailure, Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		init();
	}

	private void init() {
		myApplication.currentUser = new User();
		initView();
		initDatabase();
		initListener();
	}

	private void initView() {
		btnLogin = (Button) findViewById(R.id.btn_login);
		mUsername = (EditText) findViewById(R.id.mUsername);
		mPassword = (EditText) findViewById(R.id.mPassword);
		textviewFailure = (TextView) findViewById(R.id.failure_title);
	}

	private void initListener() {
		btnLogin.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			btnLogin.setClickable(false);
			stopInput();
			username = mUsername.getText().toString();
			password = mPassword.getText().toString();
			login();
			break;
		}
	}

	private void login() {
		showLoadingDialog("登录中……");
		String url = myApplication.url + "login.htm";
		Map<String, String> myMap = new HashMap<String, String>();
		myMap.put("accessToken", "5C9.yx0S");
		myMap.put("userName", username);
		myMap.put("passWord", password);
		HttpClientThread.getmHttpClientThread().post(url, myMap, new HttpResultHandle() {

			@Override
			public void onSuccess(String response) {
				String code = JsonUtils.getValue(response, "code");
				if ("0".equals(code)) {
					onSaveUserName();
					myApplication.currentUser.setUserName(username);
					Intent intent = new Intent(LoginActivity.this, MainActivity.class);
					startActivity(intent);
					dismissLoadingDialog();
					finish();
				} else {
					loginFailure = JsonUtils.getValue(response, "msg");
					mHandler.sendEmptyMessage(MSG_LOGIN);
					btnLogin.setClickable(true);
				}
			}

			@Override
			public void onFailure(int statusCode) {
				loginFailure = "连接服务器失败，状态码：" + statusCode;
				mHandler.sendEmptyMessage(MSG_LOGIN);
				btnLogin.setClickable(true);
			}
		});
	}

	/**
	 * 将用户名存储到SharedPreferences
	 */
	private void onSaveUserName() {
		SharedPreferences mSharedPreferences = getSharedPreferences(myApplication.sharedPreferencesFlag, Context.MODE_PRIVATE);
		Set<String> set = getUsernameSet();
		set.add(username);
		mSharedPreferences.edit().putStringSet("usernames", set).commit();
	}

	/**
	 * 获取SharedPreferences的历史用户名Set数组
	 */
	private Set<String> getUsernameSet() {
		SharedPreferences mSharedPreference = getSharedPreferences(myApplication.sharedPreferencesFlag, Context.MODE_PRIVATE);
		return mSharedPreference.getStringSet("usernames", new HashSet<String>());
	}

	/**
	 * 隐藏输入法
	 */
	private void stopInput() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(LoginActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 初始化数据库
	 */
	private void initDatabase() {
		getAllClient();
	}

	/**
	 * 获取所有客户信息
	 */
	private void getAllClient() {
		String url = myApplication.url + "listClient.htm";
		Map<String, String> myMap = new HashMap<String, String>();
		myMap.put("accessToken", "5C9.yx0S");
		myMap.put("pageNum", "0");
		myMap.put("numPerPage", "20");
		HttpClientThread.getmHttpClientThread().post(url, myMap, new HttpResultHandle() {

			@Override
			public void onSuccess(String response) {
				onSaveUserName();
				String code = JsonUtils.getValue(response, "code");
				if ("0".equals(code)) {
					// Log.i("Long", response);
					try {
						JSONObject jsonObject = new JSONObject(response);
						JSONArray jsonArray = jsonObject.getJSONArray("list");
						SamappDB samappDB = new SamappDB(LoginActivity.this, MyApplication.getApplicationInstance().databaseVesion);
						for (int i = 0; i < jsonArray.length(); i++) {
							String json = jsonArray.getString(i);
							Client client = GsonUtil.getGson().fromJson(json, Client.class);
							Log.i("Long", samappDB.insertByObject(client) + "");
						}
						Cursor cursor = samappDB.select();
						// cursor.moveToPosition(0);
						Log.i("Long", "数据库里面记录条数：" + cursor.getCount());
					} catch (JSONException e) {
						e.printStackTrace();
					}
				} else {
					getClientFailure = JsonUtils.getValue(response, "msg");
					mHandler.sendEmptyMessage(MSG_GET_ALL_CLIENT);
				}
			}

			@Override
			public void onFailure(int statusCode) {
				getClientFailure = "连接服务器失败，状态码：" + statusCode;
				mHandler.sendEmptyMessage(MSG_GET_ALL_CLIENT);
			}
		});
	}
}
